<template>
  <div :class="$style.wrap">
    <ContentWrap>
      <FormContainer :column="5">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="90px">
          <!-- <el-form-item prop="mscCustomerName" label="MSC客户名称">
            <el-input v-model="formData.mscCustomerName" placeholder="请输入MSC客户名称" clearable></el-input>
          </el-form-item> -->
          <el-form-item prop="legalPerson" label="经销商法人">
            <el-input v-model="formData.legalPerson" placeholder="请输入经销商法人" clearable></el-input>
          </el-form-item>
          <el-form-item prop="credentialNo" label="法人身份证号">
            <el-input v-model.trim="formData.credentialNo" placeholder="请输入法人身份证号" clearable></el-input>
          </el-form-item>
          <el-form-item prop="customerName" label="客户姓名">
            <el-input v-model="formData.customerName" placeholder="请输入客户姓名" clearable></el-input>
          </el-form-item>
          <el-form-item prop="customerPhone" label="客户电话">
            <el-input v-model.trim="formData.customerPhone" placeholder="请输入客户电话" clearable></el-input>
          </el-form-item>
          <!-- <el-form-item prop="mscCustomerCode" label="MSC客户编码">
            <el-input v-model.trim="formData.mscCustomerCode" placeholder="请输入MSC客户编码" clearable></el-input>
          </el-form-item> -->
          <el-form-item prop="businessStatus" label="营业状态">
            <SelectForDict :code.sync="formData.businessStatus" dict-type-code="KQ_OPERATING_STATUS" placeholder="请选择营业状态" clearable filterable></SelectForDict>
          </el-form-item>
          <el-form-item prop="handler" label="分配坐席">
            <StaffSearch v-model="formData.handler" placeholder="请选择分配坐席" clearable></StaffSearch>
          </el-form-item>
          <el-form-item prop="businessTypeCode" label="经营类型">
            <SelectForDict :code.sync="formData.businessTypeCode" dict-type-code="KQ_BUSINESS_TYPE" placeholder="请选择经营类型" clearable filterable></SelectForDict>
          </el-form-item>
          <el-form-item prop="officeCode" label="办事处">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/office/ref/page"
              placeholder="请选择办事处"
              lable-name="name"
              value-name="code"
              method="get"
              :value.sync="formData.officeCode"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="status" label="客情启用状态">
            <el-select v-model="formData.status" placeholder="请选择客情启用状态" clearable filterable>
              <el-option label="启用" :value="1" />
              <el-option label="停用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item prop="maintainState" label="维护状态">
            <el-select v-model="formData.maintainState" placeholder="请选择维护状态" clearable filterable>
              <el-option label="维护" :value="1" />
              <el-option label="未维护" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item :span="24">
            <div class="button-container" style="padding-top:0">
              <Button @click="resetForm">重置</Button>
              <Button type="primary" enter @click="queryHandle">查询</Button>
            </div>
          </el-form-item>
        </el-form>
      </FormContainer>
      <div class="button-container" style="padding-top:0">
        <Button type="primary" @click="toEditHandle">编辑</Button>
        <ExportPane :table-config="tableConfig" :data-source="selectionList" :query-data-fun="queryHandle" :export-file="exportFile" filename="客户管理" extension="xls">导出</ExportPane>
        <DialogUpload ref="export" title="导入" text="导入" :show-file-num="false" :on-change="onChangeHandle" :on-remove="removeHandle" :on-exceed="onExceed" :limit="1" :exist-file-list="fileList" @confirm="onConfirmHandle"></DialogUpload>
        <Button type="primary" @click="enableOrDisableHandle('enable')">启用</Button>
        <Button type="primary" @click="enableOrDisableHandle('disable')">停用</Button>
      </div>
      <table-box ref="table" no-request :other-filters="otherFilters" :table-config="tableConfig" :other-raw="otherRaw" @selection-change="selectionChange">
        <el-table-column slot="before" type="selection" width="50" align="center" />
      </table-box>
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import SelectForDict from '@/components/SelectForDict'
import ExportPane from '@/components/ExportPane'
import StaffSearch from '@/components/StaffSearch'
import DialogUpload from '@/components/Upload/DialogUpload'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import { ccDict } from '@/api/dataDict'
import { filtersRaw, pageRequsetBody } from '@/utils'
import { careCustomerExport, careCustomerImport, careCustomerInfoEnableBat, careCustomerInfoDisableBat } from '@/api/guestCare'
export default {
  name: 'ClientManage',
  components: {
    ContentWrap,
    FormContainer,
    SelectForDict,
    ExportPane,
    StaffSearch,
    DialogUpload,
    SearchSelectPicker
  },
  data() {
    return {
      formData: {
        // mscCustomerName: '',
        legalPerson: '',
        credentialNo: '',
        customerName: '',
        customerPhone: '',
        // mscCustomerCode: '',
        businessStatus: '',
        handler: '',
        businessTypeCode: '',
        officeCode: '',
        status: '',
        maintainState: ''
      },
      formRules: {

      },
      // table-box
      tableConfig: {
        interfacePath: '/call-center/api/v1/careCustomerInfo/page',
        pageFlag: true,
        hideFuncBar: true,
        sort: 'createTime',
        order: 'desc',
        setting: [
          {
            prop: 'index',
            label: '序号',
            width: 80,
            align: 'center',
            formatData: (val) => {
              return val.keyIndex + 1
            }
          },
          {
            label: '经销商法人',
            width: '120',
            prop: 'legalPerson',
            className: 'table-click-text',
            isButton: true,
            clickFun: this.toDetail
          },
          {
            label: 'MSC客户编码',
            width: '120',
            prop: 'mscCustomerCode'
          },
          {
            label: 'MSC客户名称',
            width: '120',
            prop: 'mscCustomerName'
          },
          {
            label: '营业状态',
            width: '120',
            prop: 'businessStatus',
            propEnum: {
              appCode: 'call-center',
              domainCode: 'marketing',
              dictTypeCode: 'KQ_OPERATING_STATUS'
            }
          },
          {
            label: '经营类型',
            width: '120',
            prop: 'businessTypeName'
            // formatData: this.getBusinessTypeName
          },
          {
            label: '客户姓名',
            width: '120',
            prop: 'customerName'
          },
          {
            label: '客户电话',
            width: '120',
            prop: 'customerPhone'
          },
          {
            label: '客户级别',
            width: '120',
            prop: 'customerLevel',
            propEnum: {
              appCode: 'call-center',
              domainCode: 'marketing',
              dictTypeCode: 'KQ_CUSTOMER_LEVEL'
            }
          },
          {
            label: '分配坐席',
            width: '140',
            formatData: v => {
              if (v.handler) {
                return `${v.handlerName}(${v.handler})`
              }
              return ''
            }
          },
          {
            label: '加盟日期',
            width: '120',
            prop: 'joiningDate'
          },
          {
            label: '开业日期',
            width: '120',
            prop: 'openingDate'
          },
          {
            label: '从业年限',
            width: '120',
            prop: 'workingYears'
          },
          {
            label: '经营模式',
            width: '120',
            prop: 'businessModel',
            propEnum: {
              appCode: 'call-center',
              domainCode: 'marketing',
              dictTypeCode: 'KQ_BUSINESS_MODEL'
            }
          },
          {
            label: '维护状态',
            width: '120',
            prop: 'id',
            formatData: v => v.id ? '维护' : '未维护'
          },
          {
            label: '启用状态',
            width: '120',
            prop: 'status',
            formatData: v => v.status === undefined ? '' : v.status === 1 || v.status === '1' ? '启用' : '停用'
          }
        ]
      },
      otherFilters: [],
      selectionList: [],
      businessTypeList: [],
      fileList: [],
      otherRaw: {}
    }
  },
  created() {
    this.getBusinessDict()
  },
  methods: {
    // 启用停用
    enableOrDisableHandle(type) {
      if (this.selectionList.length <= 0) {
        this.$message.info('请选择要操作的数据！')
        return
      }
      const ids = this.selectionList.map(e => {
        return e.id
      }).filter(e => {
        return e !== undefined
      })
      if (type === 'enable') {
        careCustomerInfoEnableBat(ids).then(res => {
          this.refreshTable('onPage')
          this.$message.success('启用成功！')
        })
      } else {
        careCustomerInfoDisableBat(ids).then(res => {
          this.refreshTable('onPage')
          this.$message.success('停用成功！')
        })
      }
    },
    // 刷新table-box
    refreshTable(page) {
      this.$nextTick(() => {
        this.$refs.table.initTableData(page)
      })
    },
    // 重置查询条件
    resetForm() {
      this.$refs.form.resetFields()
    },
    // 查询
    queryHandle(type) {
      return this.$refs.form.validate().then(() => {
        const otherFilters = []
        const otherRaw = {}
        const equal = ['credentialNo', 'customerPhone', 'businessStatus', 'handler', 'officeCode', 'status']
        const inner = []
        for (const key of Object.keys(this.formData)) {
          let v = this.formData[key]
          if (v === '' || v === undefined || v === null) {
            continue
          }
          if (key === 'officeCode' && v) {
            otherRaw.officeCode = v
            continue
          }
          if (key === 'maintainState') {
            if (v === 1) {
              otherFilters.push(filtersRaw('id', '', 'not null'))
            } else {
              otherFilters.push(filtersRaw('id', '', 'is null'))
            }
            continue
          }
          if (equal.includes(key)) {
            otherFilters.push(filtersRaw(key, v, '='))
          } else if (inner.includes(key)) {
            if (v instanceof Array) {
              v = `[${v.join(',')}]`
            } else {
              v = `[${v}]`
            }
            otherFilters.push(filtersRaw(key, v, 'in'))
          } else {
            otherFilters.push(filtersRaw(key, v, 'like'))
          }
        }
        this.otherFilters = otherFilters
        this.otherRaw = otherRaw
        if (type === 'export') {
          return otherFilters
        } else {
          this.refreshTable()
        }
      })
    },
    // 导出文件
    exportFile() {
      return this.queryHandle('export').then(data => {
        const body = {
          pageFlag: true,
          filtersRaw: data,
          paramsRaw: this.otherRaw,
          rows: 10000,
          page: 1
        }
        return careCustomerExport(pageRequsetBody(body))
      })
    },
    // 获取经营类型字典
    getBusinessDict() {
      ccDict('KQ_BUSINESS_TYPE').then(res => {
        this.businessTypeList = res.data
      })
    },
    // 获取经营类型名称
    getBusinessTypeName(row) {
      const v = (row.businessTypeCode || '').split(',')
      const t = []
      for (const i of v) {
        const name = this.$getNameByDataDict(i, this.businessTypeList)
        if (name) {
          t.push(name)
        }
      }
      return t.join(',')
    },
    // 选择数据
    selectionChange(v) {
      this.selectionList = v
    },
    // 跳转到详情
    toDetail(row) {
      const { mscCustomerCode, mscCustomerName, credentialNo, legalPerson, id } = row
      this.$router.push({ name: 'ClientManageEdit', query: { mscCustomerCode, mscCustomerName, credentialNo, id, legalPerson, type: 'preview', title: '详情' }})
    },
    // 编辑
    toEditHandle() {
      if (this.selectionList.length === 1) {
        const row = this.selectionList[0]
        const { mscCustomerCode, mscCustomerName, credentialNo, legalPerson, id } = row
        this.$router.push({ name: 'ClientManageEdit', query: { mscCustomerCode, mscCustomerName, credentialNo, legalPerson, id }})
      } else {
        this.$message.info('请选择一条数据编辑！')
      }
    },
    // 导入
    onConfirmHandle(fileList) {
      if (fileList.length > 0) {
        const formData = new FormData()
        formData.append('file', fileList[0].raw)
        // 导入提示
        const loading = this.$loading({
          lock: true,
          text: '导入中，请稍等...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        careCustomerImport(formData).then(res => {
          this.$message.success('导入成功！')
          this.refreshTable()
          this.fileList = []
          this.$refs.export.cancelAllHandle()
        }).finally(() => {
          loading.close()
        })
      }
      //  else {
      //   this.$message.info('没有选择导入文件！')
      // }
    },
    onChangeHandle(file, fileList) {
      this.fileList = fileList
    },
    removeHandle(file, fileList) {
      this.fileList = fileList.map((list) => {
        return list.raw
      }).filter(e => {
        return e !== undefined
      })
    },
    // 超出最大上传个数
    onExceed() {
      this.$message.info('每次最多只能导入一个文件')
    }
  }
}
</script>
<style lang='scss' module>
.wrap{
  tr{
    background-color: white !important;
  }
}
</style>
